Django unleshed
Setting the environment
# virtualenvwraper
export WORKON_HOME=$HOME/.venvs
export PROJECT_HOME=$HOME/Documents/projects/python
export VIRTUALENVWRAPPER_SCRIPT=/usr/local/bin/virtualenvwrapper.sh
source /usr/local/bin/virtualenvwrapper_lazy.sh
Makefile
# Makefile
#
# Frederico Sales | Bernard Rodriguez | Pedro Hote
# <frederico.sales@uab.ufjf.br> | <bernard.rodriguez@uab.ufjf.br> | <pedro.hote@uab.ufjf.br>
# 2022
#
#
## settings
#
.PHONY: all \
help \
run \
clean \
migrate \
migrations \
superuser \
clear \
install \
update \
shell \
app \
db \
crypto \
static \
pgdump \
ignore
#
## PATH's
#
ARG := $1
PORT := 8000
DB_USER := 'frederico'
DATABASE := 'fsales'
PROJECT := 'fredericosales'
SRC := src/
VENV_BIN_DIR := /Users/frederico/.venvs/${PROJECT}/bin
ACTIVATE := ${VENV_BIN_DIR}/activate
PYTHON_BIN := ${VENV_BIN_DIR}/python
PIP_BIN := ${VENV_BIN_DIR}/pip
MANAGE := ${SRC}/manage.py
REQUIREMENTS := requirements/requirements.txt
DUMP := scripts/${PROJECT}-`date +"%Y-%m-%d_%H-%M-%S"`.json
DATE := `date +"%Y-%m-%d_%H-%M-%S"`
#
## targets
#
#: Do nothing.
all:
@clear
@echo ""
@echo "This target do nothing."
@echo "Try make help."
@echo ""
#: Display help and targets.
help:
@clear
@echo "Display this help, and targets."
@echo ""
@echo "--------------------------------------------------"
@grep -B1 -E "^[a-zA-Z0-9_-]+\:([^\=]|$$)" Makefile \
| grep -v -- -- \
| sed 'N;s/\n/###/' \
| sed -n 's/^#: \(.*\)###\(.*\):.*/\2###\1/p' \
| column -t -s '###'
@echo "--------------------------------------------------"
@echo ""
#: Run django application on default port: 8000
run:
${PYTHON_BIN} ${MANAGE} runserver 0.0.0.0:${PORT}
#: Light cleaning.
clean:
@clear
@find . -name "*.pyc" -exec rm -f {} +
@find . -type d -name "__pycache__" -exec rm -rf {} +
@find . -type d -name ".DS_Store" -exec rm -rf {} +
#: Heavy clening.
clear:
@clear
@find . -name "*.pyc" -exec rm -f {} +
@find . -type d -name "__pycache__" -exec rm -rf {} +
@find . -type d -name ".DS_Store" -exec rm -rf {} +
@find . -name "[0][0]*.py" -exec rm -f {} +
#: Migration
migrations:
${PYTHON_BIN} ${MANAGE} makemigrations ${ARG}
#: Migrate
migrate:
${PYTHON_BIN} ${MANAGE} migrate
#: Update the project requirements.
update:
${PIP_BIN} install -U pip setuptools wheel
${PIP_BIN} install -U -r ${REQUIREMENTS}
#: Create the superuser.
superuser:
${PYTHON_BIN} ${MANAGE} createsuperuser
#: Duh self explanatory...
install:
${PIP_BIN} install -U pip setuptools wheel
${PIP_BIN} install -r ${REQUIREMENTS}
#: Run the freaking shell.
shell:
${PYTHON_BIN} ${MANAGE} shell
#: Create an application.
.ONESHELLL:
app:
@mkdir ${SRC}/${ARG}
${PYTHON_BIN} ${MANAGE} startapp ${SRC}/${ARG}
#: Enter the SGDB matrix.
db:
${PYTHON_BIN} ${MANAGE} dbshell
#: Dump the database to script folder.
dump:
${PYTHON_BIN} ${MANAGE} dumpdata --indent=4 -a -o ${DUMP}
#: Generate the cryptographic key for encrypted fields.
crypto:
${PYTHON_BIN} ${MANAGE} generate_encryption_key
#: Collect all static files and update in project.
static:
${PYTHON_BIN} ${MANAGE} collectstatic
#: Dump the database to a file.
pgdump:
@pg_dump -U ${DB_USER} -d ${DATABASE} -Z 9 -f scripts/${PROJECT}-${DATE}.sql.gz
#: Update gitignore files.
ignore:
@git rm -r --cached .
@git add .
@git commit -m "Update gitignore: ${DATE}."
Super secret (confidential)
Remember to add the config.json to .gitignore DUMMY!
Remember: "there is no try! do, or do not."
with open(os.path.join('scripts', 'config.json')) as f:
CONFIG = json.load(f)
Guido Van Rossun: "STOP using execption in vain"
Configuration file
config.json model
{
"SECRET_KEY" : "7d2daabd7b43f1424a216c158a0c467b7d444f6b12afcf1ef508980410191c18",
"DEBUG" : "True",
"ENGINE" : "django.db.backends.postgresql",
"NAME" : "cliffburton",
"USER" : "AsaAkira",
"PASSWORD" : "some#complicated#freaking#super#safe#passwor:D;-}o0",
"HOST" : "localhost",
"PORT" : "5432",
"LANGUAGE_CODE" : "pt-BR",
"TIME_ZONE" : "America/Sao_Paulo",
"USE_I18N" : "True",
"USE_TZ" : "True",
"STATIC_URL" : "/static/",
"MEDIA_URL" : "/media/",
"CK_UPLOADS" : "/uploads/",
"APP_ID" : "81c191014089805fe1fcfa21b6f444d7b764c0a851c612a4241f34b7dbaad2d7",
"SCHEME_TOGGLE" : "True",
"COLOR_SCHEME" : "light",
"ENCRYPTION_KEY" : "Gtp47PZP7-GtffUi9HUL01NdJzc7OfODYLlIb4PajJQ=",
"APP_ID" : "5ce81e76dcab7b5d88280f38f87974b566e36846",
"EMAIL_BACKEND" : "django.core.mail.backends.smtp.EmailBackend",
"EMAIL_HOST" : "smtp.gmail.com",
"EMAIL_USE_TLS" : "True",
"EMAIL_PORT" : "587",
"EMAIL_HOST_USER" : "mail@domain.example",
"EMAIL_HOST_PASSWORD" : "oh_crap!@#"
}
postgresql settings
DATABASES = {
'default': {
'ENGINE' : CONFIG['ENGINE'],
'NAME' : CONFIG['NAME'],
'USER' : CONFIG['USER'],
'PASSWORD' : CONFIG['PASSWD'],
'HOST' : CONFIG['HOST'],
'PORT' : CONFIG['PORT'],
}
}
sqlite settings
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mydatabase',
}
}
External logging
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '{name} {levelname} {asctime} {module} {process:d} {thread:d} {message}',
'style': '{',
},
'simple': {
'format': '{levelname} {message}',
'style': '{',
},
},
}
Native logging
DJANGO_LOG_LEVEL = {
'level': os.getenv('DJANGO_LOG_LEVEL', 'WARNING'),
}
HTML messages
About html returns((When a browser requests a service from a web server, an error might occur, and the server might return an error code like "404 Not Found". It is common to name these errors HTML error messages. But these messages are something called HTTP status messages. In fact, the server always returns a message for every request. The most common message is 200 OK https://www.w3schools.com/tags/ref_httpmessages.asp.))
code |
message |
description |
100 |
Continue |
The server has received the request headers, and the client should proceed to send the request body |
101 |
Switching Protocols |
The requester has asked the server to switch protocols. |
103 |
Early Hints |
Used with the Link header to allow the browser to start preloading resources while the server prepares a response |
2XX: successful
code |
message |
description |
200 |
OK |
A link list. The user can select a link and go to that location. Maximum five addresses |
201 |
Created |
The request has been fulfilled, and a new resource is created |
202 |
Accepted |
The request has been accepted for processing, but the processing has not been completed |
203 |
Non-Authoritative Information |
The request has been successfully processed, but is returning information that may be from another source |
204 |
No Content |
The request has been successfully processed, but is not returning any content |
205 |
Reset Content |
The request has been successfully processed, but is not returning any content, and requires that the requester reset the document view |
206 |
Partial Content |
The server is delivering only part of the resource due to a range header sent by the client |
3XX: redirection
code |
message |
description |
300 |
Multiple Choices |
The request is OK (this is the standard response for successful HTTP requests) |
301 |
Moved Permanently |
The request has been fulfilled, and a new resource is created |
302 |
Found |
The requested page has moved temporarily to a new URL |
303 |
See Other |
The requested page can be found under a different URL |
304 |
Not Modified |
Indicates the requested page has not been modified since last requested |
307 |
Temporary Redirect |
The requested page has moved temporarily to a new URL |
308 |
Permanent Redirect |
The requested page has moved permanently to a new URL |
4xx: client error
code |
message |
description |
400 |
Bad Request |
The request cannot be fulfilled due to bad syntax |
401 |
Unauthorized |
For use when authentication is possible but has failed or not yet been provided |
402 |
Payment Required |
Reserved for future use |
403 |
Forbidden |
The request was a legal request, but the server is refusing to respond to it |
404 |
Not Found |
The requested page could not be found but may be available again in the future |
405 |
Method Not Allowed |
A request was made of a page using a request method not supported by that page |
406 |
Not Acceptable |
The server can only generate a response that is not accepted by the client |
407 |
Proxy Authentication Required |
The client must first authenticate itself with the proxy |
408 |
Request Timeout |
The server timed out waiting for the request |
409 |
Conflict |
The request could not be completed because of a conflict in the request |
410 |
Gone |
The requested page is no longer available |
411 |
Length Required |
The "Content-Length" is not defined. The server will not accept the request without it |
412 |
Precondition Failed |
The precondition given in the request evaluated to false by the server |
413 |
Request Too Large |
The server will not accept the request, because the request entity is too large |
414 |
Request-URI Too Long |
Occurs when you convert a POST request to a GET request with a long query information |
415 |
Unsupported Media Type |
The server will not accept the request, because the media type is not supported |
416 |
Range Not Satisfiable |
The client has asked for a portion of the file, but the server cannot supply that portion |
417 |
Expectation Failed |
The server cannot meet the requirements of the Expect request-header field |
5xx: server error
code |
message |
description |
500 |
Internal Server Error |
A generic error message, given when no more specific message is suitable |
501 |
Not Implemented |
The server either does not recognize the request method, or it lacks the ability to fulfill the request |
502 |
Bad Gateway |
The server was acting as a gateway or proxy and received an invalid response from the upstream serve |
503 |
Service Unavailable |
The server is currently unavailable (overloaded or down) |
504 |
Gateway Timeout |
The server was acting as a gateway or proxy and did not receive a timely response from the upstream server |
505 |
HTTP Version Not Supported |
The server does not support the HTTP protocol version used in the request |
511 |
Network Authentication Required |
The client needs to authenticate to gain network access |